﻿CREATE PROCEDURE [acms].[Menu_Put]
	@Id int, 
	@SiteId int,
	@Name varchar(20),
	@ParentId int,
	@IncludeParent bit,
	@DefaultForAllPosts bit,
	@VersionId timestamp,
	@IdOut int output,
	@ParentPathOut varchar(255) output,
	@VersionIdOut timestamp output
AS

	if @ParentID = 0
		set @ParentId = null

	declare @UpdatePostMenus bit

	set @UpdatePostMenus = @DefaultForAllPosts

	if exists (select null from Menu_View where Id = @Id) begin
		if @UpdatePostMenus = 1
			select @UpdatePostMenus = (DefaultForAllPosts * -1 ) + 1 From Menu_View Where Id = @Id
		
		update Menus
		set
			[SiteId] = @SiteId,
			[Name] = @Name,
			[ParentId] = @ParentId,
			[IncludeParent] = @IncludeParent,
			[DefaultForAllPosts] = @DefaultForAllPosts
		where
			Id = @Id
			and VersionId = @VersionId
		if @@RowCount = 0
			return -100
		else
			set @IdOut = @Id
			
	end
	else if @Id is null or @Id = 0 begin
		insert into Menus
			([SiteId], [Name], [ParentId], [IncludeParent], [DefaultForAllPosts])
		values
			(@SiteId, @Name, @ParentId, @IncludeParent, @DefaultForAllPosts)
		set @IdOut = @@Identity
	end
	else begin
		return -200
	end
	
	if @UpdatePostMenus = 1 begin
		insert [acms].[PostMenu]
			(PostId, MenuId, Included)
		select Id, @IdOut, 1 
		from [acms].[Posts] 
		where Id not in 
			(select PostId From [acms].[PostMenu_View] Where MenuId = @IdOut)
	end
	
	select @ParentPathOut = ParentPath, @VersionIdOut = VersionId from Menu_View where Id = @IdOut
	
RETURN 0;